package com.aaa.front.config;

import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * ProjectName sbm_rabbitmq_producer_demo_20230605
 * Author lx
 * Date 2023/06/05 下午 03:20
 * Version 1.0.0
 * Description 死信队列配置
 */
@Configuration //Bean
public class SpringRabbitDeadLetterMQConfig {

    public final static String BUSINESS_EXCHANGE_TOPIC_1 = "business_exchange_topic_1";
    public final static String BUSINESS_QUEUE_1 = "business_queue_1";
    public final static String ROUTING_KEY = "dead.letter.rk.#";
    public final static String DEAD_LETTER_EXCHANGE_TOPIC_1 = "dead_letter_exchange_topic_1";
    public final static String DEAD_LETTER_QUEUE_1 = "dead_letter_queue_1";

    /**
     * 定义交换机
     * @return 业务交换机
     */
    @Bean
    public Exchange businessExchange(){
        return ExchangeBuilder.topicExchange(BUSINESS_EXCHANGE_TOPIC_1).build();
    }

    /**
     * 业务队列
     */
    @Bean
    public Queue businessQueue(){
        //实例化业务队列的参数
        Map<String, Object> argumentsMap = new HashMap<>();
        //队列一旦创建就无法使用，所以想再次使用就把原来队列删除或者创建新的队列
        //设置业务队列的保存消息时长
        argumentsMap.put("x-message-ttl",1800000);
//        argumentsMap.put("x-max-length",10);
        //把当前队列和死信交换机进行绑定
        argumentsMap.put("x-dead-letter-exchange",DEAD_LETTER_EXCHANGE_TOPIC_1);
        argumentsMap.put("x-dead-letter-routing-key",ROUTING_KEY);
        return QueueBuilder.durable(BUSINESS_QUEUE_1).withArguments(argumentsMap).build();
        //return new Queue(BUSINESS_QUEUE_1,true,false,false,argumentsMap);
    }

    /**
     * 把业务交换机绑定业务队列
     * @return
     */
    @Bean
    public Binding bingingBusinessExchangeToQueue(){
        return BindingBuilder.bind(businessQueue()).to(businessExchange()).with(ROUTING_KEY).noargs();
    }

    /**
     * 定义交换机
     * @return 死信交换机
     */
    @Bean
    public Exchange deadLetterExchange(){
        return ExchangeBuilder.topicExchange(DEAD_LETTER_EXCHANGE_TOPIC_1).build();
    }

    /**
     * 死信队列
     */
    @Bean
    public Queue deadLetterQueue(){
        return QueueBuilder.durable(DEAD_LETTER_QUEUE_1).build();
    }

    /**
     * 把死信交换机绑定死信队列
     * @return
     */
    @Bean
    public Binding bingingDeadLetterExchangeToQueue(){
        return BindingBuilder.bind(deadLetterQueue()).to(deadLetterExchange()).with(ROUTING_KEY).noargs();
    }



}
